import { HttpStatus, Injectable } from '@nestjs/common';
import { UserEntity } from '../entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CommonService } from '@/modules/core/base/common.service';
import { CommonPaginationServiceDto } from '@/modules/core/dto/pagination.dto';
import { UpdateUserDto } from '../dto/updateUser.dto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
    private readonly commonService: CommonService,
  ) {}

  async detail(userId: string) {
    const user = await this.userRepository.findOneOrFail({
      where: {
        id: userId,
      },
      relations: ['accessToken'],
    });
    return user;
  }
  async findOne(username: string): Promise<UserEntity | undefined> {
    const user = await this.userRepository.findOne({
      where: [
        {
          username: username,
        },
        {
          phone: username,
        },
        {
          email: username,
        },
      ],
      relations: ['accessToken'],
    });
    return user;
  }
  async create(userInfo: any) {
    try {
      const user = new UserEntity();
      user.username = userInfo.username;
      user.password = userInfo.password;
      user.phone = userInfo.phone;
      user.email = userInfo.email;
      return await user.save();
    } catch (error) {
      console.log(error.message);
      return {
        statusCode: HttpStatus.BAD_REQUEST,
        message: 'create user fail',
      };
    }
  }
  async list(options: CommonPaginationServiceDto) {
    const { withTrash, onlyTrash } = options;
    let qb = this.userRepository.createQueryBuilder('user');
    if (withTrash) {
      qb = qb.withDeleted();
      if (onlyTrash) qb = qb.where('user.deleteAt IS NOT NULL');
    }
    const users = await qb.orderBy('user.createdAt', 'DESC').getMany();
    return this.commonService.pagination(users, options);
  }

  async delete(id: string) {
    try {
      const user = await this.detail(id);
      return await this.userRepository.remove(user);
    } catch (error) {
      return {
        statusCode: HttpStatus.NOT_FOUND,
        msg: error.message,
      };
    }
  }

  async update(id, body: UpdateUserDto) {
    if (!id) {
      return {
        message: 'id不能为空',
        statusCode: 400,
      };
    }
    try {
      const user = await this.detail(id);
      user.username = body.username;
      user.email = body.email;
      if (body.password && body.password.trim().length > 0) {
        user.password = body.password;
      }
      user.phone = body.phone;
      return await user.save();
    } catch (error) {
      return {
        statusCode: HttpStatus.NOT_FOUND,
        msg: error.message,
      };
    }
  }
}
